package com.zhouchao.mvp.login;

import android.os.Handler;
import android.os.Message;

import com.zhouchao.mvp.Entity.User;

/**
 * 描述：
 * zhougan
 * 2019/2/28
 **/
public class LoginPresenter implements LoginContract.ILoginPresenter{
    private LoginContract.ILoginModel loginModel;
    private LoginContract.ILoginView loginView;
    private User user;

    public LoginPresenter(LoginContract.ILoginView loginView) {
        this.loginView=loginView;
        loginModel=LoginModel.getInstance();
    }

    private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            setProgressBarVisibility(false);
            if(message.what==1){
                loginView.onLoginSuccess();
            }else{
                loginView.onLoginFailure((String) message.obj);
            }
            return true;
        }
    });

    @Override
    public void login(String name, String password) {
        if(user==null){
             user=new User(name,password);
        }else{
            user.setName(name);
            user.setPassword(password);
        }

        String invalite = loginModel.invalite(user);
        if (!invalite.equals(LoginModel.INVALITE_SUCCESS)) {
            loginView.onLoginFailure(invalite);
            return;
        }
        setProgressBarVisibility(true);
        loginModel.login(user, new LoginContract.ILoginModel.Callback() {
            @Override
            public void onSuccess() {
               handler.sendEmptyMessage(1);
            }

            @Override
            public void onFailure(String msg) {
                handler.sendMessage(handler.obtainMessage(0,msg));
            }
        });
    }

    @Override
    public void clear() {
        loginView.onClear();
    }

    @Override
    public void setProgressBarVisibility(Boolean show) {
        loginView.onProgressBarVisibility(show);
    }

    @Override
    public void onDestroy() {
        loginView=null;
    }
}
